package handler

import (
	"2212b/examination/api/handler/request"
	"2212b/examination/consts"
	"2212b/examination/internal/dao"
	"2212b/examination/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func Register(c *gin.Context) {
	var req request.RegisterReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "参数信息失败",
			"Data": err.Error(),
		})
		return
	}
	user := model.User{}
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "已存在",
			"Data": nil,
		})
		return
	}
	create := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
		Student:  req.Student,
		FullName: req.FullName,
	})
	if !create {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "创建注册失败",
			"Data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"Data": true,
	})
}

func Login(c *gin.Context) {
	var req request.LoginReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "参数信息失败",
			"Data": err.Error(),
		})
		return
	}
	user := model.User{}
	dao.GetOneByFields(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "不存在",
			"Data": nil,
		})
		return
	}
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().UnixMilli() + 1*2,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "生成token失败",
			"Data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登录成功",
		"Data": token,
	})
}

func UpdateToken(c *gin.Context) {

}
